package com.pc.tas.web;

import com.pc.cloud.services.*;
import com.pc.cloud.utils.NamePair;
import com.pc.tas.learning.trace.index.TraceSearchArgs;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.Map.Entry;

@Controller
public class AnaylyzeController {
	
	@Autowired
	private SearchServices searchServices;

	private void getSumJSON(Map<String,SearchResults> results, JSONArray jitems, int total) throws Exception {
		JSONObject jo = new JSONObject();
		jo.put("name", "result");
		for(String type : results.keySet()){
			SearchResults sr = results.get(type);
			Collection<NamePair> sums = sr.getSum();
			if(sums != null && sums.size()>0) {
				for(NamePair np : sums) {
					System.out.println(np.getName() + " : " + np.getValue());
					String name = "metric_" + type + "^" + np.getName();
					//String vn = np.getName().replace(".", "-");
					//System.out.println(vn + " : " + np.getValue());	
					jo.put(name, np.getValue());
				}
			}
		}		
		jitems.put(jo);	
	}
	
	private void getSumFacetJSON(Map<String,SearchResults> results, JSONArray jitems,int total) throws Exception {
		for(String type : results.keySet()){
			SearchResults sr = results.get(type);
			Map<String,Collection<FacetSearchRow>> sumFacets = sr.getSumFacets();
			if(sumFacets != null && sumFacets.size() > 0) {
				for(Entry<String,Collection<FacetSearchRow>> entry : sumFacets.entrySet()) {
					Collection<FacetSearchRow> fsrs = entry.getValue();
					for(FacetSearchRow fsr : fsrs){
						JSONObject jo = new JSONObject();
						String[] names = fsr.getName().split("\\^\\~");
						jo.put("name", names[0]);
						if(names.length == 2){
							jo.put("url", names[1]);
						}
						Collection<NamePair> nps = fsr.getPairs();
						for(NamePair np : nps) {
							String name = "metric_" + type + "^" + np.getName();
							jo.put(name, np.getValue());						
						}
						
						jitems.put(jo);
					}
				}
			}
		}
	}
	
	@RequestMapping("/trace/summaryAnalyze")
	@ResponseBody
	public String summaryAnalyze(@RequestParam String beginDate,@RequestParam String endDate,@RequestParam String dimension,@RequestParam String metrics) {
		try{
			String viewType = null;
			String type = null;
			MetricArg sarg = null;
			List<MetricArg> metricFields = new ArrayList<MetricArg>();
			String[] metric = metrics.split(",");
			for (String key : metric) {
				if (key.startsWith("metric_sum_")) {
					String subkey = key.substring(11);
					String[] keys = subkey.split("_");
					if (keys.length > 1) {
						viewType = keys[0];
					}
					String[] types = keys[keys.length - 1].split("\\^");
					type = types[0];
					sarg = new MetricArg(types[1], MetricArg.SUM);
					metricFields.add(sarg);
				} else if (key.startsWith("metric_count_")) {
					String subkey = key.substring(13);
					String[] keys = subkey.split("_");
					if (keys.length > 1) {
						viewType = keys[0];
					}
					String[] types = keys[keys.length - 1].split("\\^");
					type = types[0];
					sarg = new MetricArg(types[1], MetricArg.COUNT);
					metricFields.add(sarg);
				} else if (key.startsWith("metric_distinct_count_")) {
					String subkey = key.substring(22);
					String[] keys = subkey.split("_");
					if (keys.length > 1) {
						viewType = keys[0];
					}
					String[] types = keys[keys.length - 1].split("\\^");
					type = types[0];
					sarg = new MetricArg(types[1], MetricArg.DISTINCT_COUNT);
					metricFields.add(sarg);
				}
			}
			TraceSearchArgs tsa = new TraceSearchArgs();
			Map<String,String[]> ranges = new HashMap<String,String[]>();
			JSONArray jitems = new JSONArray();

			
			String[] times = new String[2];
			times[0] = beginDate;
			times[1] = endDate;
			ranges.put("time", times);
			
			if(ranges.size() > 0) {
				tsa.setOtherRange(ranges);
			}
			
			Map<String,SearchResults> results = new HashMap<String,SearchResults>();
			
			FacetQueryArg fs = new FacetQueryArg();
			fs.setFacetField(dimension);
			fs.setMetricFields(metricFields);
			tsa.setType(type);
			tsa.getFacetQueryFields().add(fs);
		
			SearchResults res = searchServices.search(tsa);
			results.put(type, res);
			int total = 0;
			this.getSumFacetJSON(results,jitems,total);
			
			return jitems.toString();
		}catch(Throwable e){
			e.printStackTrace();
			return "error:" + e.getMessage();
		}
	}
	
	@RequestMapping("/trace/seAnalyze")
	@ResponseBody
	public String searchEngieerAnalyze(@RequestParam String beginDate,@RequestParam String endDate) {
		try{					
			TraceSearchArgs tsa = new TraceSearchArgs();
			String viewType = null;
			Map<String,String[]> ranges = new HashMap<String,String[]>();
			JSONArray jitems = new JSONArray();

			
			String[] times = new String[2];
			times[0] = beginDate;
			times[1] = endDate;
			ranges.put("time", times);
			
			if(ranges.size() > 0) {
				tsa.setOtherRange(ranges);
			}
			String dimension = "search-engine";

			Map<String,SearchResults> results = new HashMap<String,SearchResults>();
			List<MetricArg> metricFields = new ArrayList<MetricArg>();
			metricFields.add(new MetricArg(dimension, MetricArg.DISTINCT_COUNT));
			FacetQueryArg fs = new FacetQueryArg();
			fs.setFacetField(dimension);
			fs.setMetricFields(metricFields);
			tsa.setType("view");
			tsa.getFacetQueryFields().add(fs);
		
			SearchResults res = searchServices.search(tsa);
			results.put("view", res);
			int total = 0;
			this.getSumFacetJSON(results, jitems, total);
			
			return jitems.toString();
		}catch(Throwable e){
			e.printStackTrace();
			return "error:" + e.getMessage();
		}
	}
}
